package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.db.Analysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AnalysisService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisMapper analysisMapper;

    /**
     * 定时统计的业务逻辑
     *  1、查询日志表数据
     *  2、将统计结果写入到统计表(保存/更新)
     */
    public void analysis() throws ParseException {
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");
        //1、查询日志表数据
        //1.1 新注册用户数
        Integer regNum = logMapper.queryByLogTimeAndType(today, "0102");
        //1.2 登陆次数
        Integer logNum = logMapper.queryByLogTimeAndType(today, "0101");
        //1.3 活跃用户数
        Integer actNum = logMapper.queryByLogTime(today);
        //1.4 次日留存用户数
        Integer numRetention1d = logMapper.queryNumRetention1d(today, yesterday);
        //2、根据日志（record_date）查询统计表数据
        Date recordDate = new SimpleDateFormat("yyyy-MM-dd").parse(today);
        QueryWrapper<Analysis> qw = new QueryWrapper<>();
        qw.eq("record_date",recordDate);
        Analysis analysis = analysisMapper.selectOne(qw);
        //2.1 数据不存在，保存
        if(analysis == null) {
            analysis = new Analysis();
            analysis.setRecordDate(recordDate);
            analysis.setNumActive(actNum);
            analysis.setNumRetention1d(numRetention1d);
            analysis.setNumRegistered(regNum);
            analysis.setNumLogin(logNum);
            analysis.setCreated(new Date());
            analysisMapper.insert(analysis);
        }else {
            //2.2 数据存在，更新
            analysis.setNumActive(actNum);
            analysis.setNumRetention1d(numRetention1d);
            analysis.setNumRegistered(regNum);
            analysis.setNumLogin(logNum);
            analysisMapper.updateById(analysis);
        }
    }
}
